package com.blrs.web.controller.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blrs.common.annotation.Anonymous;
import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.uuid.IdUtils;
import com.blrs.system.domain.SysUploadFile;
import com.blrs.system.domain.vo.SysFileVo;
import com.blrs.system.domain.vo.SysFilesVo;
import com.blrs.system.service.ISysUploadFileService;
import com.blrs.system.service.ISysUploadService;
import com.blrs.web.oss.OosService;
import liquibase.pro.packaged.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.blrs.common.config.RuoYiConfig;
import com.blrs.common.constant.Constants;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.file.FileUploadUtils;
import com.blrs.common.utils.file.FileUtils;
import com.blrs.framework.config.ServerConfig;

import static com.blrs.common.utils.file.FileUtils.setAttachmentResponseHeader;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysUploadFileService sysUploadFileService;
    @Autowired
    private OosService oosService;
    @Autowired
    private ISysUploadService sysUploadService;
    private static final String FILE_DELIMETER = ",";






    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

//    @PostMapping("/uploadFileOSS")
//    @Anonymous
//    public AjaxResult uploadFileOSS( MultipartFile file) throws Exception{
//        String s = oosService.uploadFile(file, file.getOriginalFilename());
//        return AjaxResult.success(s);
//    }
        @GetMapping("/deleteFileOSS")
    @Anonymous
    public AjaxResult deleteFileOSS(String path) throws Exception{
            return oosService.deleteFile(path) ? AjaxResult.success() : AjaxResult.error("删除失败！");
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @Anonymous
    public AjaxResult uploadFile( SysFileVo file) throws Exception
    {
        Long count=sysUploadService.selectSysUploadByCount(file.getBusinessCode());
        if(count==0){
            return AjaxResult.error("类型编号不存在！");
        }
        try{
            SysUploadFile sysUploadFile=new SysUploadFile();
            sysUploadFile.setFileName(file.getFile().getOriginalFilename());
            //获取上传的文件路径和新文件名称
            Map<String, String> stringStringMap = oosService.uploadFile(file.getFile(), file.getFile().getOriginalFilename());
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", stringStringMap.get("pathUrl"));
            ajax.put("fileName", stringStringMap.get("path"));
            ajax.put("newFileName",stringStringMap.get("newFileName"));
            ajax.put("originalFilename", file.getFile().getOriginalFilename());
            sysUploadFile.setContent(file.getContent());
            sysUploadFile.setFileSize(String.valueOf(file.getFile().getSize()));
            sysUploadFile.setNewFileName(stringStringMap.get("newFileName"));
            sysUploadFile.setUrl(stringStringMap.get("pathUrl"));
            sysUploadFile.setPhyPath(stringStringMap.get("path"));
            sysUploadFile.setFileType(file.getFile().getOriginalFilename().substring(file.getFile().getOriginalFilename().lastIndexOf(".")));
            if(file.getId()==null){
                sysUploadFile.setOrganizationId(SecurityUtils.getOrgId());
                sysUploadFile.setOrganizationName(SecurityUtils.getOrgName());
                sysUploadFile.setBusinessId(file.getBusinessId());
                sysUploadFile.setBusinessCode(file.getBusinessCode());
                sysUploadFile.setId(IdUtils.fastUUID());
                sysUploadFile.setDelFlag(0);
                sysUploadFile.setOrganizationName(SecurityUtils.getUsername());
                sysUploadFile.setDepartmentId(String.valueOf(SecurityUtils.getDeptId()));
                sysUploadFile.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
                sysUploadFile.setCreationBy(SecurityUtils.getUsername());
                sysUploadFile.setOperateId(String.valueOf(SecurityUtils.getUserId()));
                ajax.put("id", sysUploadFile.getId());
                sysUploadFileService.insertSysUploadFile(sysUploadFile);
            }else{
                //删除原来文件
                SysUploadFile s=sysUploadFileService.selectSysUploadFileById(file.getId());
               boolean f= oosService.deleteFile(s.getPhyPath());
                sysUploadFile.setId(file.getId());
                if(f){
                    sysUploadFileService.updateSysUploadFile(sysUploadFile);
                }
            }
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
//        try
//        {
//
//            Calendar calendar = Calendar.getInstance();
//            SysUploadFile sysUploadFile=new SysUploadFile();
//            sysUploadFile.setFileName(file.getFile().getOriginalFilename());
//            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file.getFile());
//            String url = serverConfig.getUrl() + fileName;
//            AjaxResult ajax = AjaxResult.success();
//            String newFileName=FileUtils.getName(fileName);
//            ajax.put("url", url);
//            ajax.put("fileName", fileName);
//            ajax.put("newFileName",newFileName);
//            ajax.put("originalFilename", file.getFile().getOriginalFilename());
//            sysUploadFile.setContent(file.getContent());
//            sysUploadFile.setFileSize(String.valueOf(file.getFile().getSize()));
//            sysUploadFile.setNewFileName(newFileName);
//            sysUploadFile.setUrl(url);
//            sysUploadFile.setPhyPath(filePath+"/"+ calendar.get(Calendar.YEAR)+"/"+((calendar.get(Calendar.MONTH)+1)<10?"0"+(calendar.get(Calendar.MONTH)+1): (calendar.get(Calendar.MONTH)+1))+"/"+(calendar.get(Calendar.DATE)<10?("0"+calendar.get(Calendar.DATE)):calendar.get(Calendar.DATE)));
//            sysUploadFile.setFileType(newFileName.substring(newFileName.lastIndexOf(".")));
//            if(file.getId()==null){
//                sysUploadFile.setOrganizationId(SecurityUtils.getOrgId());
//                sysUploadFile.setOrganizationName(SecurityUtils.getOrgName());
//                sysUploadFile.setBusinessId(file.getBusinessId());
//                sysUploadFile.setBusinessCode(file.getBusinessCode());
//                sysUploadFile.setId(IdUtils.fastUUID());
//                sysUploadFile.setDelFlag(0);
//                sysUploadFile.setOrganizationName(SecurityUtils.getUsername());
//                sysUploadFile.setDepartmentId(String.valueOf(SecurityUtils.getDeptId()));
//                sysUploadFile.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
//                sysUploadFile.setCreationBy(SecurityUtils.getUsername());
//                sysUploadFile.setOperateId(String.valueOf(SecurityUtils.getUserId()));
//                ajax.put("id", sysUploadFile.getId());
//                sysUploadFileService.insertSysUploadFile(sysUploadFile);
//            }else{
//                //删除原来文件
//                SysUploadFile s=sysUploadFileService.selectSysUploadFileById(file.getId());
//               boolean f= FileUtils.deleteFile(s.getPhyPath()+"/"+s.getNewFileName());
//                sysUploadFile.setId(file.getId());
//                if(f){
//                    sysUploadFileService.updateSysUploadFile(sysUploadFile);
//                }
//
//            }
//
//            return ajax;
//        }
//        catch (Exception e)
//        {
//            return AjaxResult.error(e.getMessage());
//
//        }

    }
    @PostMapping("/test")
    @Anonymous
    public  Map<String, String> test(MultipartFile file) throws Exception{
        Map<String, String> stringStringMap = oosService.uploadFile(file, file.getOriginalFilename());
        return stringStringMap;
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/uploadHonor")
    public AjaxResult uploadHonorFile( SysFileVo file) throws Exception
    {
            Calendar calendar = Calendar.getInstance();
            SysUploadFile sysUploadFile=new SysUploadFile();
            sysUploadFile.setFileName(file.getFile().getOriginalFilename());
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file.getFile());
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            String newFileName=FileUtils.getName(fileName);
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName",newFileName);
            ajax.put("originalFilename", file.getFile().getOriginalFilename());
            sysUploadFile.setContent(file.getContent());
            sysUploadFile.setFileSize(String.valueOf(file.getFile().getSize()));
            sysUploadFile.setNewFileName(newFileName);
            sysUploadFile.setUrl(url);
            sysUploadFile.setPhyPath(filePath+"/"+ calendar.get(Calendar.YEAR)+"/"+((calendar.get(Calendar.MONTH)+1)<10?"0"+(calendar.get(Calendar.MONTH)+1): (calendar.get(Calendar.MONTH)+1))+"/"+(calendar.get(Calendar.DATE)<10?("0"+calendar.get(Calendar.DATE)):calendar.get(Calendar.DATE)));
            sysUploadFile.setFileType(newFileName.substring(newFileName.lastIndexOf(".")));
            return ajax;
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles( SysFilesVo files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files.getFiles())
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @PostMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
     if (resource != null && resource.contains("https://changsha42.zos.ctyun.cn")){
         String downloadName = StringUtils.substringAfterLast(resource, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
         setAttachmentResponseHeader(response, downloadName);
         writeBytesFromUrl(resource, response.getOutputStream());
     }else {
                 try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
     }

    }

    private void writeBytesFromUrl(String urlStr, OutputStream os) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        try (InputStream is = connection.getInputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }
    }

    private void writeBytesFromFile(String filePath, OutputStream os) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }
    }
}
